package persistence.dao;

import java.sql.ResultSet;
import java.sql.SQLException;

import persistence.db.DataSet;
import persistence.db.DatabaseConnector;
import persistence.model.AbstractModel;
import persistence.model.AnneeEtude;
import persistence.model.Formation;

public class FormationDAO extends AbstractDAO{
	
	private Formation formation;

	public FormationDAO() {
		setTableName("FORMATION");
	}
	
	public FormationDAO(Formation f) {
		this();
		formation = f;
		setId(formation.getId());
	}

	public DataSet all() {
		return new DataSet(this);
	}

	public AbstractModel makeModel(ResultSet rset) {
		try {
			this.setId(rset.getInt("id_Formation"));
			
			DataSet anneesEtudesSet = AnneeEtude.all().filter("FK_AE_FORMATION = " + getId());
			
			return new Formation(getId(),
					rset.getString("nomFormation"),
					rset.getString("descriptionFormation"),
					anneesEtudesSet);
		} catch (SQLException e) {
			System.out.println("makeModel error");
			e.printStackTrace();
		}
		return null;
	}

	public void save() {
		String query;
		ResultSet result;
			query = "INSERT INTO " + getTableName() + " VALUES ( S_PK_"+ getTableName() +".nextval, '" + formation.getNomFormation() + "', '" + formation.getDescriptionFormation() +"')";
			System.out.println("query : " + query);
			/* Execute la requete */
			result = DatabaseConnector.getInstance().execute(query);
			setId(this.getId()); /* Mise a jour de l'identifiant */
	}

	public void save(int id) {
		String query;
		ResultSet result;
			query = "UPDATE " + getTableName() +
				" SET nomFormation = '" + formation.getNomFormation() +
				"', descriptionFormation = '" + formation.getDescriptionFormation() +
				" ' WHERE ID_"+ getTableName() + " = " + id;
			/* Execute la requete */
			result = DatabaseConnector.getInstance().execute(query);
	}
}
